package com.test13;

import java.util.Arrays;
import java.util.EventListener;
import java.util.EventObject;

public class MyTest_05 {

    public static void main(String[] args) {
        YootkEventSourceObject sourceObject = new YootkEventSourceObject("www.yootk.com");
        sourceObject.addListener(new YootkEventListener());
        sourceObject.setMessage("沐言科技：www.yootk.com");
    }
}

/**
 * 事件对象
 */
class TootkEventObject extends EventObject {
    private Object source;  // 事件源

    public TootkEventObject(Object source) {
        super(source);
        this.source = source;
    }

    @Override
    public Object getSource() {
        return source;
    }

    public void setSource(Object source) {
        this.source = source;
    }
}

/**
 * 事件监听器
 */
class YootkEventListener implements EventListener {

    public void fire(TootkEventObject event) {
        YootkEventSourceObject sourceObject = (YootkEventSourceObject) event.getSource();
        System.out.println("【数据修改】message = " + sourceObject.getMessage());
    }
}

/**
 * 事件源
 */
class YootkEventSourceObject {
    private String message;
    private YootkEventListener[] listeners;
    private int foot = 0;

    public YootkEventSourceObject(String message) {
        this.listeners = new YootkEventListener[5];
        this.message = message;
    }

    public void addListener(YootkEventListener listener) {
        if (foot < this.listeners.length) {
            this.listeners[this.foot++] = listener;
        }
    }

    public void notifyInvoke() {
        for (YootkEventListener listener : this.listeners) {
            if (listener != null) {
                listener.fire(new TootkEventObject(this));
            }
        }
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        if (!this.message.equals(message)) {
            this.message = message;
            this.notifyInvoke();
        }
    }
}
